package net.freebytes.ssmp.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import net.freebytes.ssmp.entity.Permission;
import net.freebytes.ssmp.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 权限
 *
 * @author 千里明月
 * @date 2021/7/20
 **/
@Service
public class PermService extends ServiceImpl<PermissionMapper, Permission> {
    @Autowired
    private PermissionMapper permissionMapper;

    private static LoadingCache<String, List<Permission>> permissionCache;

    public PermService() {
        //启用缓存，容量为1000，过期时间为30分钟
        permissionCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(30, TimeUnit.MINUTES).
                build(new CacheLoader<String, List<Permission>>() {
                    @Override
                    public List<Permission> load(String uid) throws Exception {
                        //如没有该缓存键值，那么就写入缓存
                        return permissionMapper.allPermissionByUid(uid);
                    }
                });
    }

    public boolean insertPerm(Permission p) {
        Permission one = super.getOne(new QueryWrapper<Permission>().lambda().eq(Permission::getName, p.getName()));
        if (one != null) {
            throw new RuntimeException(("权限已存在"));
        }
        return super.save(p);
    }

    public List<Permission> cacheAllPermissionByUid(String uid) {
        List<Permission> permissions = null;
        try {
            permissions = permissionCache.get(uid);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return permissions;
    }

    public void deleteCache(String uid) {
        permissionCache.asMap().remove(uid);
    }

}
